package org.example.day06;

/**
 * 第二章节:2.3.3.4: volatile关键字之后的代码不可以重排到volatile之前(屏障)
 **/
public class MyThread13 {
    private static long x = 0;
    private static long y = 0;
    private static long a = 0;
    private static long b = 0;
    volatile private static long c = 0;
    volatile private static long d = 0;

    private static long count = 0;

    public static void main(String[] args) throws InterruptedException {
        for (;;){
            x = 0;
            y = 0;
            a = 0;
            b = 0;
            c = 0;
            d = 0;
            count++;
            Thread t1 = new Thread(new Runnable() {
                @Override
                public void run() {
                    x = b;
                    c = 101; //volatile x = b 和 a = 1的指令不能重排序了，中间有了屏障
                    a = 1;
                }
            });
            Thread t2 = new Thread(new Runnable() {
                @Override
                public void run() {
                    y = a;
                    d = 201; //volatile
                    b = 1;
                }
            });
            t1.start();
            t2.start();
            t1.join();
            t2.join();
            String showStr = "count=" + count + " " + x + "," + y;
            //不会出现x=1 y=1 的情况了
            if(x == 0 && y == 0){
                System.err.println(showStr);
                break;
            }else{
                System.out.println(showStr);
            }
        }
    }
}
